from  sqlalchemy.orm import sessionmaker
from com.Database import create_db_engine
from com.BookEntity import BookEntity
class BookRepository:

    def __init__(self, uri):
        self.db_engine = create_db_engine(uri)

    def add(self, name, author, price):
        book = BookEntity(name, author, price)
        session = sessionmaker(bind=self.db_engine, expire_on_commit=False)
        db_session = session()
        db_session.add(book)
        try:
            db_session.commit()
            return book
        except:
            db_session.rollback()
        finally:
            db_session.close()

    def list(self, page, size, name):
        session = sessionmaker(bind=self.db_engine, expire_on_commit=False)
        db_session = session()
        if name is None or len(name) == 0:
            books = db_session.query(BookEntity).offset((page - 1) * size).limit(
                size).all()
            db_session.close()
            return books
        else:
            books = db_session.query(BookEntity).filter(
                BookEntity.name.like("%" + name + "%")).offset((page - 1) * size).limit(
                size).all()
            db_session.close()
            return books

    def count(self, name):
        session = sessionmaker(bind=self.db_engine, expire_on_commit=False)
        db_session = session()
        if name is None or len(name) == 0:
            count = db_session.query(BookEntity).count()
            db_session.close()
            return count
        else:
            count = db_session.query(BookEntity).filter(BookEntity.name.like("%" + name + "%")).count()
            db_session.close()
            return count